package demos;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class MyThread implements Runnable {

    @Override
    public void run() {

    }
}

/**
 * Callable 有异常，有返回值，实现方法不一样
 */
class MyThread2 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("come in");
        try { Thread.sleep(2000); } catch (Exception e) { e.printStackTrace(); }
        return 1024;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread2());

        // 同一个futureTask用两个线程去调用
        // 会发现call()只调用了一次，call函数的内容是一样的
        // 即结果相同可以直接复用
        new Thread(futureTask, "A").start();
        new Thread(futureTask, "B").start();

        System.out.println("main finish");
        System.out.println(futureTask.get());
    }
}
